package cn.com.winning.ecare.activity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import cn.com.winning.ecare.common.MyApplication;
import cn.com.winning.ecare.utils.DisplayUtil;
import cn.com.winning.ecare.utils.HTTPGetTool;
import cn.com.winning.ecare.utils.URLUtils;
import cn.com.winning.ecare.utils.UserRecord;
import cn.com.winning.ecare.widgets.CustomProgressDialog;

/**
 * 疾病百科主界面
 * @author Administrator
 *
 */
public class Health1 extends Activity
{

	private Health1 oThis = this;
	private CustomProgressDialog proDialog;// 加载框
	private Map<String, Object> map_bw; // 人体部位map
	List<Map<String, Object>> list_bw = new ArrayList<Map<String, Object>>();// 人体部位list
	private int preId = -1;
	private ImageView btnjbcx;// 疾病查询
	private Button btn_turn;// 转身
	private Button btn_sex;// 性别
	private ImageView body;// 人体
	private ImageView body_part;// 人体选择部位
	private int gender = 1;// 记录男女标记，0为女，1为男
	private int front_back = 1;// 记录前后，0为背面，1为正面
	private float screenWidth;// 窗口的宽度
	private float screenHeight;// 窗口高度
	private EditText edt_jbmc = null;// 查询框
	private TextView tv_sex;
	MyApplication myApp;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_search_disease_layout);
		myApp = (MyApplication) getApplication();
		myApp.addActivity(this);
		myApp.getUserRecords().setUsername(myApp.getAccount());
		myApp.getUserRecords().setModule("Health1@疾病百科");
		UserRecord.getInstance(myApp.getUserRecords()).init();
		
		getAssetsData();
		DisplayMetrics dm = new DisplayMetrics();
		// 取得窗口属性
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		screenWidth = dm.widthPixels;
		screenHeight = dm.heightPixels;
		// 初始化view
		findView();

		// 初始化界面数据
		GetData();

		// 点击事件
		setOnClick();
		
		
	}

	/**
	 * 主线程状态更新
	 */
	Handler myHandler = new Handler()
	{
		public void handleMessage(Message msg)
		{
			int type = msg.getData().getInt("type");
			switch (type)
			{
				case -1:
					proDialog.dismiss();
					Toast.makeText(oThis, msg.getData().getString("msg"), Toast.LENGTH_SHORT).show();
					break;
				case 0:
					proDialog.dismiss();
					break;
				case 1:
					break;

				default:
					break;
			}
		};
	};

	// 初始化view
	private void findView()
	{
		btnjbcx = (ImageView) this.findViewById(R.id.btnjbcx);
		btn_turn = (Button) this.findViewById(R.id.btn_turn);
		btn_sex = (Button) this.findViewById(R.id.btn_sex);
		body = (ImageView) super.findViewById(R.id.body);
		body_part = (ImageView) super.findViewById(R.id.body_part);// 找到你layout中对应的imageView
		edt_jbmc = (EditText) this.findViewById(R.id.edt_jbmc);
		tv_sex = (TextView) this.findViewById(R.id.tv_sex);

	}

	// 初始化界面数据
	private void GetData()
	{
		proDialog = CustomProgressDialog.createDialog(oThis);
		proDialog.setMessage("数据加载中...");
		proDialog.show();
		proDialog.setCanceledOnTouchOutside(false);
		// 这里单开一个线程和后台数据交互
		new Thread(new LoadData()).start();

	}

	class LoadData implements Runnable
	{

		public void run()
		{

			Looper.prepare();
			iniData();
			Looper.loop();
		}
	}

	private void iniData()
	{
		Message msg = myHandler.obtainMessage();
		Bundle bundle = new Bundle();
		bundle.putInt("type", 0);
		bundle.putString("msg", "");
		msg.setData(bundle);
		myHandler.sendMessage(msg);
	}

	// 点击事件
	private void setOnClick()
	{
		// 切换人物前后
		btn_turn.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				Drawable drawable = null;
				if (front_back == 0)
				{
					front_back = 1;
					if (gender == 1)
					{
						drawable = getResources().getDrawable(R.drawable.male_front);
						body.setImageDrawable(drawable);
					}
					else if (gender == 0)
					{
						drawable = getResources().getDrawable(R.drawable.female_front);
						body.setImageDrawable(drawable);
					}

				}
				else if (front_back == 1)
				{
					front_back = 0;
					if (gender == 1)
					{
						drawable = getResources().getDrawable(R.drawable.male_back);
						body.setImageDrawable(drawable);
					}
					else if (gender == 0)
					{
						drawable = getResources().getDrawable(R.drawable.female_back);
						body.setImageDrawable(drawable);
					}
				}
				body_part.setImageDrawable(drawable);
			}
		});

		// 切换人物性别
		btn_sex.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				Drawable drawable = null;
				if (gender == 0)
				{
					gender = 1;// 记录男女标记，0为女，1为男
					if (front_back == 1)
					{// 记录前后，0为背面，1为正面
						drawable = getResources().getDrawable(R.drawable.male_front);
						body.setImageDrawable(drawable);
					}
					else if (front_back == 0)
					{
						drawable = getResources().getDrawable(R.drawable.male_back);
						body.setImageDrawable(drawable);
					}

					btn_sex.setBackgroundResource(R.drawable.bg_btn_item_sex);
					tv_sex.setText("男性");
				}
				else if (gender == 1)
				{
					gender = 0;
					if (front_back == 1)
					{// 记录前后，0为背面，1为正面
						drawable = getResources().getDrawable(R.drawable.female_front);
						body.setImageDrawable(drawable);
					}
					else if (front_back == 0)
					{
						drawable = getResources().getDrawable(R.drawable.female_back);
						body.setImageDrawable(drawable);
					}
					btn_sex.setBackgroundResource(R.drawable.bg_btn_item_sex_fe);
					tv_sex.setText("女性");
				}
				body_part.setImageDrawable(drawable);

			}
		});

		// 疾病查询
		btnjbcx.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View v)
			{

				String diseasename = edt_jbmc.getText().toString().trim();
				if (diseasename != null && !diseasename.equals(""))
				{
					Intent intent = new Intent(Health1.this, Health3.class);

					intent.putExtra("diseasename", diseasename);
					intent.putExtra("type", "Health1");
					startActivity(intent);
				}
				else
				{
					Toast.makeText(Health1.this, "请输入查询条件！", Toast.LENGTH_SHORT).show();
				}
			}
		});

	}

	// 在这里实现onTouchEvent
	public boolean onTouchEvent(MotionEvent event)
	{
		// 在这里判断一下如果是按下操作就获取坐标然后执行方法
		if (event.getAction() == MotionEvent.ACTION_DOWN)
		{
			// 获取图片的绝对位置坐标，图片的实际高度，宽度
			int[] location = new int[2];
			body.getLocationOnScreen(location);
			int body_x = location[0];
			int body_y = location[1];
			int height = body.getHeight();
			int wigth = body.getWidth();
			// 触屏坐标
			float x = event.getX();
			float y = event.getY();

			// 触屏坐标换算成相对图片原点坐标
			x = x - (body_x + wigth / 2);
			y = y - (body_y + height / 2);

			// 根据不同分辨率手机图片放大比例，进行缩放，然后在于body.json中的区域范围比较
			x = x * 548 / height;
			y = y * 380 / wigth;
			String sdate = getSelectData(x, y);
			if (!sdate.equals(""))
			{
				String[] str = sdate.split(",");

				int resID = getResources().getIdentifier(str[1], "drawable", "cn.com.winning.ecare.activity");
				Drawable image = getResources().getDrawable(resID);

				body_part.setImageDrawable(image);

				if (str[0].equals("头部"))
				{
					Intent intent = new Intent(Health1.this, Health5.class);
					startActivity(intent);
				}
				else
				{
					Intent intent = new Intent(Health1.this, Health2.class);
					intent.putExtra("partname", str[0]);
					intent.putExtra("sex", gender);
					startActivity(intent);
				}

			}
		}
		return super.onTouchEvent(event);
	}

	/**
	 * 解析body.json
	 * 
	 * @return
	 */
	public List getAssetsData()
	{
		AssetManager am = this.getAssets();
		try
		{
			InputStream is = am.open("body.json");
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
			byte[] bt = new byte[1024];
			int len = 0;
			while ((len = is.read(bt)) != -1)
			{
				outputStream.write(bt, 0, len);
			}

			outputStream.close();
			is.close();

			JSONObject obj;
			JSONArray jsonArr, jsonArr2;
			try
			{
				obj = new JSONObject(outputStream.toString());
				jsonArr = new JSONArray(obj.getString("body"));
				Map<String, Object> map_bw2; // selectarea
				List<Map<String, Object>> list_bw2;
				for (int i = 0; i < jsonArr.length(); i++)
				{

					JSONObject js = jsonArr.getJSONObject(i);
					jsonArr2 = new JSONArray(js.getString("selectArea"));
					list_bw2 = new ArrayList<Map<String, Object>>();
					for (int j = 0; j < jsonArr2.length(); j++)
					{
						JSONObject js2 = jsonArr2.getJSONObject(j);

						map_bw2 = new HashMap<String, Object>();
						map_bw2.put("x1", js2.getString("x1"));
						map_bw2.put("x2", js2.getString("x2"));
						map_bw2.put("y1", js2.getString("y1"));
						map_bw2.put("y2", js2.getString("y2"));
						list_bw2.add(map_bw2);
					}

					map_bw = new HashMap<String, Object>();
					map_bw.put("gender", js.getString("gender"));
					map_bw.put("front_back", js.getString("front_back"));
					map_bw.put("partName", js.getString("partName"));
					map_bw.put("iconName", js.getString("iconName"));
					map_bw.put("selectArea", list_bw2);
					list_bw.add(map_bw);
				}
			}
			catch (JSONException e)
			{
				e.printStackTrace();
			}

		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return list_bw;
	}

	/**
	 * 判断坐标，选择坐标在范围内，返回部位信息
	 * 
	 * @return
	 */
	public String getSelectData(float x, float y)
	{
		String selectdate = "";
		for (int i = 0; i < list_bw.size(); i++)
		{
			List<Map<String, Object>> list_area = (List<Map<String, Object>>) list_bw.get(i).get("selectArea");
			int flag1 = Integer.valueOf(list_bw.get(i).get("gender").toString());
			int flag2 = Integer.valueOf(list_bw.get(i).get("front_back").toString());
			for (int j = 0; j < list_area.size(); j++)
			{
				float x1 = Float.valueOf(list_area.get(j).get("x1").toString());
				float x2 = Float.valueOf(list_area.get(j).get("x2").toString());
				float y1 = Float.valueOf(list_area.get(j).get("y1").toString());
				float y2 = Float.valueOf(list_area.get(j).get("y2").toString());

				if (flag1 == gender && flag2 == front_back)
				{
					if (x > x1 && x < x2 && y > y1 && y < y2)
					{
						selectdate = list_bw.get(i).get("partName").toString() + "," + list_bw.get(i).get("iconName").toString();
					}
				}
			}
		}
		return selectdate;
	}

}
